#include "saisieabs.h"

int jourStart=16;

int jourEnd=15;


DialogAbs::DialogAbs(QWidget *parent ): QDialog(parent)
{
    setupUi(this);

    absTable->setSortingEnabled(true);
    absTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    absTable->setSelectionMode(QAbstractItemView::SingleSelection);
    absTable->setColumnWidth(0,105);
    absTable->setColumnWidth(1,100);
    /// As no slection = -1 we start with a number<> -1
    curRow=-4;
    createCompleters();
    changed=true;
}

void DialogAbs::setDate(QDate date){
    absDate->setDate(date);
}

void DialogAbs::clearTable() {
    absTable->setRowCount(0);
}

void DialogAbs::print() {

}






void DialogAbs::createCompleters(){

    QSqlQuery query("SELECT * FROM Employ");

    nomList.clear();
    prenomList.clear();
    cinList.clear();

    while (query.next()) {
        nomList.append(query.value(0).toString());
        prenomList.append(query.value(1).toString());
        cinList.append(query.value(3).toString());
    }

    QStringList nom2=nomList;
    QStringList pnom2=prenomList;
    nom2.removeDuplicates();
    pnom2.removeDuplicates();
    nom2.sort();
    pnom2.sort();
    nameLE->addItems(nom2);
    surNameLE->addItems(pnom2);

    nomComp= new QCompleter(nomList, this);
    prenomComp= new QCompleter(prenomList, this);
    //
    //prenomComp->setCompletionMode(QCompleter::InlineCompletion);
    prenomComp->setCaseSensitivity(Qt::CaseInsensitive);
    nomComp->setCaseSensitivity(Qt::CaseInsensitive);
    nameLE->setCompleter(nomComp);
    surNameLE->setCompleter(prenomComp);

    QList <QString> causes;
    causes<<"Maladie"<<"Inconnue"<<"Autre";
    QCompleter *causeComp= new QCompleter(causes, this);
    causeComp->setCompletionMode(QCompleter::InlineCompletion);
    causeComp->setCaseSensitivity(Qt::CaseInsensitive);
    raisonLE->setCompleter(causeComp);

}

void DialogAbs::setMonth(const QDate & min, const QDate & max ){
    calendarWidget->setDateRange(min,max);
}

void DialogAbs::setSel(QModelIndex ind){
    curRow=ind.row();
    absTable->selectRow(curRow);
    qDebug()<<curRow;
}



void DialogAbs::showAbs(int year, int month){
    /// we update the table to show

    monthLB->setText(QDate::longMonthName(month));
    QSqlQuery query("SELECT * FROM Absences ");
    QString monthStr,yearStr,curMonth,curYear;
    qDebug()<<month;
    curMonth.setNum(month);
    if (month <10) {
        curMonth.prepend("0");
    }
    curYear.setNum(year);


    dates.clear();
    raisons.clear();
    duree.clear();
    cin.clear();

    while (query.next()) {
        /// we chop the date to get the month and year
        monthStr=query.value(1).toString().section('-',1,1);
        yearStr= query.value(1).toString().section('-',0,0);
        /// We only display absences correpondign to currnet month
        //qDebug()<<curMonth<<monthStr;
        if ( monthStr==curMonth && yearStr==curYear){
            cin.append(query.value(0).toString());
            dates.append(query.value(1).toString());
            raisons.append(query.value(2).toString());
            duree.append(query.value(3).toString());
            //qDebug()<<"Affiche l'abscence"<<query.value(0).toString();
        }
    }
    clearTable();
    if (dates.size()!=0){
        for (int i=absTable->rowCount();i<dates.size();i++){

            absTable->insertRow( absTable->rowCount());
        }

        qDebug()<<"filling table absences";
        for (int i=0;i<dates.size();i++){
            int ind=cinList.indexOf(cin.at(i));
            // le cin est non trouvé Possibe ? : due a la corruption de la databaseou dans le case l'empolyé a été supprime mais pas l'abscence
            if (ind==-1){
                qDebug()<<"Invalid data in column CIN. Operation aborted "  ;
                continue;
            }


            QTableWidgetItem *newItem=new QTableWidgetItem(cin.at(i),0);
            newItem->setFlags(Qt::ItemIsSelectable);
            absTable->setItem(i, 0, newItem);

            newItem = new QTableWidgetItem(nomList.at(ind),0);
            newItem->setFlags(Qt::ItemIsSelectable);
            absTable->setItem(i, 1, newItem);


            newItem = new QTableWidgetItem(prenomList.at(ind),0);
            newItem->setFlags(Qt::ItemIsSelectable);
            absTable->setItem(i, 2, newItem);

            newItem = new QTableWidgetItem(dates.at(i),0);
            newItem->setFlags(Qt::ItemIsSelectable);
            absTable->setItem(i, 3, newItem);


            newItem = new QTableWidgetItem(raisons.at(i),0);
            newItem->setFlags(Qt::ItemIsSelectable);
            absTable->setItem(i, 4, newItem);

            newItem = new QTableWidgetItem(duree.at(i),0);
            newItem->setFlags(Qt::ItemIsSelectable);
            absTable->setItem(i, 5, newItem);
        }
    }
}



void DialogAbs::addAbs() {

    if( nameLE->currentText().isEmpty() || absDate->date().toString("yyyy-MM-dd")=="2000-01-01"){
        QMessageBox::critical(0,"Impossible","Veuillez d'abord saisir la raison et la date de l'abscence",QMessageBox::Ok);
        return;
    }

    if( raisonLE->text().isEmpty()){
        raisonLE->setText("---");
    }

    QSqlQuery query= QSqlQuery();
    if(!query.exec("SELECT cin FROM Employ where `nom`='"+nameLE->currentText()+ "' AND `prenom`='"+surNameLE->currentText()+"'")){
        qDebug()<<query.lastError().text();
    }
    query.next();
    /// Pas d'employé correspondant
    if (!query.isValid()){
        QMessageBox::critical(0,"Impossible",tr("Aucun employé nommé %1 %2").arg(nameLE->currentText()).arg(surNameLE->currentText()),QMessageBox::Ok);

        return;
    }

    curcin= query.value(0).toString();

    QString J="1";
    QString d=absDate->date().toString("yyyy-MM-dd");
    changed=true;


    if (demiRB->isChecked()) J="1/2";



    op=QSqlQuery();
    if(!op.exec("INSERT INTO Absences (cin, date,raison,journee) VALUES ('"+curcin+"','"+d+"','"+raisonLE->text()+"','"+J+"')")){
        if (op.lastError().text().contains("Duplicate"))
            QMessageBox::critical(0,"Opération non réalisée","Impossible d'ajouter l'abscence :\n Il existe déjà une autre absence dans la mm date",QMessageBox::Ok);
        else
            QMessageBox::critical(0,"Opération non réalisée","Impossible d'ajouter l'abscence :\n"+op.lastError().text(),QMessageBox::Ok);
        return;
    }


    absTable->insertRow( absTable->rowCount());

    QTableWidgetItem *newItem = new QTableWidgetItem(curcin,0);
    newItem->setFlags(Qt::ItemIsSelectable);
    absTable->setItem(absTable->rowCount()-1, 0, newItem);

    newItem = new QTableWidgetItem(nameLE->currentText(),0);
    newItem->setFlags(Qt::ItemIsSelectable);
    absTable->setItem(absTable->rowCount()-1, 1, newItem);

    newItem = new QTableWidgetItem(surNameLE->currentText(),0);
    newItem->setFlags(Qt::ItemIsSelectable);
    absTable->setItem(absTable->rowCount()-1, 2, newItem);

    newItem = new QTableWidgetItem(d,0);
    newItem->setFlags(Qt::ItemIsSelectable);
    absTable->setItem(absTable->rowCount()-1, 3, newItem);

    newItem = new QTableWidgetItem(raisonLE->text(),0);
    newItem->setFlags(Qt::ItemIsSelectable);
    absTable->setItem(absTable->rowCount()-1, 4, newItem);

    newItem = new QTableWidgetItem(J,0);
    newItem->setFlags(Qt::ItemIsSelectable);
    absTable->setItem(absTable->rowCount()-1, 5, newItem);

}



void DialogAbs::remAbs() {
    if (absTable->currentRow()!=curRow){
        QMessageBox::critical(0,"Opération non réalisée","Sélectionnez une Absence à supprimer!",QMessageBox::Ok);
        return;
    }

    QString date,raison;
    curcin=absTable->item(curRow,0)->text();
    date=absTable->item(curRow,3)->text();
    raison=absTable->item(curRow,4)->text();
    qDebug()<<"removing at row"<<curRow<<date<<curcin;

    op=QSqlQuery();
    if(!op.exec("DELETE FROM Absences WHERE cin="+curcin+" AND date='"+date+"'")){
        QMessageBox::critical(0,"Opération non réalisée","Impossible de supprimer l'abscence :\n"+op.lastError().text(),QMessageBox::Ok);
        return;
    }

    absTable->removeRow(curRow);

}
